package com.alibaba.aliper.agent;

import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.aliper.server.interfaces.AliperRemoteControll;
import com.caucho.hessian.client.HessianProxyFactory;

public class JStatApp {
	public static Pattern pattern = Pattern.compile("([0-9]+\\.?[0-9]*)\\s*\\n");
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws Exception {
		if(args.length == 0){
			System.out.println("需要且仅仅需要一个java进程id为参数");
			System.exit(0);
		}
		String command = "jstat -gcutil " + args[0] ;
		String url = "http://10.20.129.139:8080/aliper-server/AliperServlet";

	    HessianProxyFactory factory = new HessianProxyFactory();
	    AliperRemoteControll remote = (AliperRemoteControll) factory.create(AliperRemoteControll.class, url);
		while(true){
			Thread.sleep(1000);
			Process process = Runtime.getRuntime().exec(command);
			InputStream stream = process.getInputStream();
			byte[] data = new byte[1024];
			StringBuffer buffer = new StringBuffer();
			for(int count = 0; (count = stream.read(data)) != -1;){
				buffer.append(new String(data,0,count));
			}
			String line = buffer.toString();
			
			Matcher matcher = pattern.matcher(line);
			if(matcher.find()){
				remote.report("project","arandaServer", "jstat", "gct", System.currentTimeMillis(), Double.parseDouble(matcher.group(1)));
			}
			
			
		}
		
		
	}

}
